import axios from 'axios'
import { UserModule } from '@/store/modules/user'
import { ElMessage,ElMessageBox } from 'element-plus'


const service = axios.create({
    // url = base url + request url
    baseURL: process.env.VUE_APP_BASE_API, 
    timeout: 5000
  })

  //请求拦截器
service.interceptors.request.use(
    (config:any) => {
      // Add header to every request
      if (UserModule.token) { 
        config.headers['authorization'] = UserModule.token
      }   
      // console.log("config",config);      
      return config
    },
    (error) => {
      Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    if(response.status==200){
      //从后端获取的数据
      // console.log(response.data);    
      return response.data
    }else{
      return Promise.reject(new Error('Error'))
    }  
  },
  (error) =>{
    console.log(error.message)
    ElMessage({
      message:'Error',
      type:'error',
      duration:5*1000
    })
    if(error.response.status === 400 || error.response.status === 401 || error.response.status === 500 ){
      ElMessageBox.confirm(
        '你已被登出，可以取消继续留在该页面，或者重新登录',
        'Warning',
        {
          confirmButtonText:'重新登录',
          cancelButtonText:'取消',
          type:'warning'
        }
      ).then(() => {
        UserModule.ResetToken()
        location.reload()
      })
    }
    return Promise.reject(error)
  }
)

export default service